package uf.audit.demo.controller;

import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;

import com.jfinal.plugin.activerecord.Record;

import uf.audit.demo.util.JSONUtil;
import uf.audit.tax.platform.core.annotation.Controller;
import uf.audit.tax.platform.core.db.DBProFacotry;
import uf.audit.tax.platform.core.spring.bean.ILogInfo;
import uf.audit.tax.platform.core.spring.bean.User;
import uf.audit.tax.platform.util.Utils;
import uf.audit.tax.platform.util.encryption.RSAUtil;


@Controller(url = "/pub", view = "/pages/pub")
public class PublicController extends BaseController {

	private static final Logger log = Logger.getLogger(PublicController.class);

	public static String loginPage = "/pub/login";

	public void login() {
		ILogInfo logInfo = Utils.getApplicationContext().getBean("LogInfo", ILogInfo.class);
		if (!logInfo.login(this)) {
			renderError(403);
		}
	}

	public void a() {
		String postData = getPostData();
		System.out.println(postData);
		renderSuccess();
	}

	/*public void b() {
		render("index.html");
	}
	*/
	public void hxzgqc() {
		render("hxzgqc.html");
	}

	public void logout() {
		ILogInfo logInfo = Utils.getApplicationContext().getBean("LogInfo", ILogInfo.class);
		if (!logInfo.login(this)) {
			renderError(403);
			return;
		}
	}

	public void getPublicKey() {
		String ori = "987654321";
		String publicKey = RSAUtil.rsaKeyStrMap.get("publicKey");
		Map<String, String> m = new HashMap<String, String>();
		m.put("ori", ori);
		m.put("res", publicKey);
		renderJson(m);
		System.out.println("pk：" + publicKey);
		System.out.println("加密前的字符：" + ori);
		byte[] ori2byte;
		try {
			ori2byte = ori.getBytes("utf-8");
			byte[] enc2byte = RSAUtil.RSAEncode((PublicKey) RSAUtil.rsaKeyMap.get(RSAUtil.PUBLIC_KEY), ori2byte);
			String enc2base64 = Base64.encodeBase64String(enc2byte);
			System.out.println("加密后的字符：" + enc2base64);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void rsaDecode() {
		String str = getPostData();
		System.out.println("解密前的字符：" + str);
		String jm = RSAUtil.RSADecode((PrivateKey) RSAUtil.rsaKeyMap.get(RSAUtil.PRIVATE_KEY),
				Base64.decodeBase64(str));
		System.out.println("解密后的字符：" + jm);
		renderSuccess();
	}

	private static String mUserLogin;

	public void checkUser() {
		if (mUserLogin == null) {
			Properties p;
			try {
				p = Utils.getProperties("/sysinfo.properties");
				mUserLogin = p.getProperty("muserlogin");
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (mUserLogin == null) {
				mUserLogin = "denied";
			}
		}
		log.info("mUserLogin->" + mUserLogin);
		if (mUserLogin.equalsIgnoreCase("allow")) {
			User user = Utils.getApplicationContext().getBean("User", User.class);
			boolean valid = user.checkUserToken(this);
			if (!valid) {
				Utils.setLogout(this);
				renderError();
				return;
			}
			renderSuccess();
		} else {
			renderSuccess();
		}
	}
	
	
	public void userlogin() {
		render("userlogin.html");
	}
	public void signin() {
		render("signin.html");
	}
	public void forgotPwd() {
		render("forgotPwd.html");
	}
	public void index() {
		render("index.html");
	}
	public void goodsDetail() {
		render("goodsDetail.html");
	}
	
	/**
	 * 用户注册
	 */
	public void userRegister() {
		Record rec = JSONUtil.parseRecord(getPostData());
		String name = rec.getStr("name");
		String realName = rec.getStr("realName");
		String identity = rec.getStr("xh");
		String phone = rec.getStr("phone");
		String email = rec.getStr("email");
		String srPwd = rec.getStr("srPwd");
		String findSql = "select username from usermsg where username = ?";
		List<Record> list = DBProFacotry.getPro().find(findSql,name);
		if(list.size()==0){
			String insertSql = "insert into usermsg(username,realname,userPwd,email,user_phone,identity) values(?,?,?,?,?,?)";
			DBProFacotry.getPro().update(insertSql, name,realName,srPwd,email,phone,identity);
			renderSuccess();
		}else{
			renderError();
		}
	}
	/**
	 * 用户登录
	 */
	public void uLogin() {
		Record rec = JSONUtil.parseRecord(getPostData());
		String name = rec.getStr("name");
		String pwd = rec.getStr("pwd");
		String findUsernameSql = "select username from usermsg where username = ?";
		String findUserSql = "select * from usermsg where username = ? and userPwd = ?";
		List<Record> list1 = DBProFacotry.getPro().find(findUsernameSql,name);
		List<Record> list2 = DBProFacotry.getPro().find(findUserSql,name,pwd);
		if(list1.size()==0){
			renderJson("status", "1");
		}else{
			if(list2.size()==0){
				renderJson("status", "2");
			}else{
				this.getSession().setAttribute("user", list2.get(0));
				renderSuccess();
			}
		}
		
	}
	/**
	 * 获取session中对象
	 * 
	 */
	public void getSessionUser() {
		Object obj = this.getSession().getAttribute("user");
		renderJson(obj);
	}
	
	/**
	 * 退出登录时，清空Session
	 */
	
	public void logout1() {
		this.getSession().getAttribute("user");
		// 删除session中的属性  
		removeSessionAttr("user"); 
		renderSuccess();
	}
	/**
	 * 查询车辆
	 */
	public void getBikes() {
		
		String findBikesSql = "select * from bike limit 4";
		List<Record> rec = DBProFacotry.getPro().find(findBikesSql);
		System.out.println(rec);
		renderJson(rec);
	}
	
	/**
	 * 判断是否已经该用户收藏
	 */
	
	public void isSc() {
		Record rec = JSONUtil.parseRecord(getPostData());
		//String username = rec.get("username");
		Object obj = this.getSession().getAttribute("user");
		Record rec1 = JSONUtil.parseRecord(JSONUtil.toJson(obj));
		String username = rec1.get("username");
		String xm = rec.get("xm");
		String isScSql = "select carXm from wdsc where (username=?) and (carXm=?)";
		List<Record> list = DBProFacotry.getPro().find(isScSql,username,xm);
		if(list.size()>0){
				renderJson("status", "已收藏");
		}else{
			renderJson("status", "未收藏");
		}
	}
	
	/**
	 * 我的收藏
	 */
	
	public void collection() {
		Record rec = JSONUtil.parseRecord(getPostData());
		String img = rec.get("img");
		String xm = rec.get("xm");
		String price = rec.get("price");
		String cjlx = rec.get("cjlx");
		String cjcz = rec.get("cjcz");
		String sb = rec.get("sb");
		String ljcc = rec.get("ljcc");
		String username = rec.get("username");
		String scSql = "insert into wdsc(carImg,carXm,carPrice,carCjlx,carCjzz,carSb,carLjzz,username) values(?,?,?,?,?,?,?,?)";
		DBProFacotry.getPro().update(scSql,img,xm,price,cjlx,cjcz,sb,ljcc,username);
		renderSuccess();
	}
	/**
	 * 取消收藏
	 */
	
	public void qxCollection() {
		Record rec = JSONUtil.parseRecord(getPostData());
		String xm = rec.get("xm");
		String username = rec.get("username");
		String qxScSql = "delete from wdsc where (username=?) and (carXm=?)";
		DBProFacotry.getPro().update(qxScSql,username,xm);
		renderSuccess();
	}
	
	/**
	 * 加入购物车
	 */
	
	public void addGwc() {
		
		Record rec = JSONUtil.parseRecord(getPostData());
		String xm = rec.getStr("xm");
		String price= rec.getStr("price");
		String img = rec.getStr("img");
		String num = rec.getStr("num");
		Object obj = this.getSession().getAttribute("user");
		Record rec1 = JSONUtil.parseRecord(JSONUtil.toJson(obj));
		String username = rec1.get("username");
		String findNumByXm = "select num from gwc where xm=? and username=?";
		List<Record> list = DBProFacotry.getPro().find(findNumByXm,xm,username);
		int numCar = 0;
		if(list.size()>0){
			numCar = Integer.parseInt(list.get(0).getStr("num"))+Integer.parseInt(num);
		}
		if(list.size()==0){
			String Gwcsql = "insert into gwc(xm,price,img,num,username)values(?,?,?,?,?)" ;
			DBProFacotry.getPro().update(Gwcsql,xm,price,img,num,username);
			renderSuccess();
		}else{
			if(numCar>5){
				renderJson("num","超出数量");
			}else{
				String updateCarNum = "update gwc set num = ? where xm = ? and username = ?" ;
				DBProFacotry.getPro().update(updateCarNum,numCar,xm,username);
				renderSuccess();
			}
		}
	}
	
	/**
	 * 
	 * 存车辆信息进入缓存中
	 */
	public void rent() {
		
		Record rec = JSONUtil.parseRecord(getPostData());
		String img = rec.getStr("img");
		String price = rec.getStr("price");
		String num = rec.getStr("num");
		String xm = rec.getStr("xm");
		this.getSession().setAttribute("rent",rec);
		/*Object obj = this.getSession().getAttribute("user");
		Record rec1 = JSONUtil.parseRecord(JSONUtil.toJson(obj));
		String username = rec1.get("username");
		String realname = rec1.get("realname");
		String user_phone = rec1.get("user_phone");
		String identity = rec1.get("identity");*/
		
		/*String sql = "insert into rent(img,price,num,xm,username,realname,user_phone,identity) values(?,?,?,?,?,?,?,?)";
		DBProFacotry.getPro().update(sql,img,price,num,xm,username,realname,user_phone,identity);*/
		renderSuccess();
	}
	/**
	 * 
	 * 缓存中取出车辆数据
	 */
	public void getBikeSession() {
		Object obj = this.getSession().getAttribute("rent");
		renderJson(obj);
	}
}
